/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.web.theme;

import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.option.Options;
import com.jfinal.core.JFinal;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.render.Render;
import com.jfinal.render.RenderManager;
import com.jfinal.template.Engine;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Golly
 *
 */
public class ThemeRender extends Render {

	private static Log log = Log.getLog(ThemeRender.class);

	private static Engine engine;
	private static final String contentType = "text/html; charset=" + getEncoding();
	private static String contextPath = JFinal.me().getContextPath();

	private Engine getEngine() {
		if (engine == null) {
			engine = RenderManager.me().getEngine();
		}
		return engine;
	}

	public ThemeRender(String view) {
		this.view = view;
	}

	public String getContentType() {
		return contentType;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.jfinal.render.Render#render()
	 */
	@Override
	public void render() {
		response.setContentType(getContentType());

		Map<Object, Object> data = new HashMap<Object, Object>();
		for (Enumeration<String> attrs = request.getAttributeNames(); attrs.hasMoreElements(); ) {
			String attrName = attrs.nextElement();
			data.put(attrName, request.getAttribute(attrName));
		}

		Theme theme = ThemeManager.me().getCurrentTheme();
		String html = getEngine().getTemplate(theme.getWebAbsolutePath() + view).renderToString(data);
		html = replaceSrcThemeSrcPath(html);

		try {
			response.getWriter().write(html);
		} catch (IOException e) {
			log.error("JFSA模板错误", e);
		}
//TODO:
//        RenderHelpler.actionCacheExec(html, contentType);
//        RenderHelpler.renderHtml(response, html, contentType);
	}

	public String toString() {
		return view;
	}

	public String replaceSrcThemeSrcPath(String content) {
		if (StrKit.isBlank(content)) {
			return content;
		}

		Document doc = Jsoup.parse(content);

		// 处理style中的background-image:url元素
		Elements bgImgElements = doc.select("[style*=background-image]");
		replaceStyle(bgImgElements);

		Elements dbElements = doc.select("[data-background]");
		replace(dbElements, "data-background");

		Elements incElements = doc.select("include[src]");
		replace(incElements, "src");

		Elements jsElements = doc.select("script[src]");
		replace(jsElements, "src");

		Elements imgElements = doc.select("img[src]");
		replace(imgElements, "src");

		Elements linkElements = doc.select("link[href]");
		replace(linkElements, "href");

		return doc.toString();

	}

	private void replaceStyle(Elements elements) {
		String regex = "(?<=\\()(\\S+)(?=\\))";
		String regex2 = "(?<=\\')(\\S+)(?=\\')";
		String regex3 = "(?<=\\\")(\\S+)(?=\\\")";
		Iterator<Element> iterator = elements.iterator();
		Theme theme = ThemeManager.me().getCurrentTheme();
		while (iterator.hasNext()) {
			Element element = iterator.next();
			String style = element.attr("style");
			log.debug("style属性：" + style);
			String url = getMatcher(regex, style);
			if (StrExtKit.isBlank(url)) {
				continue;
			}

			// 去除url两边的引号
			if ((url.startsWith("\'") && url.endsWith("\'"))
					|| (url.startsWith("\"") && url.endsWith("\""))) {
				url = url.substring(1, url.length() - 1);
			}
			log.debug("style属性中提取的首个URL：" + url);

			// 处理src、href中的元素
			if (StrExtKit.isBlank(url)
					|| url.startsWith("//")
					|| url.toLowerCase().startsWith("http")
					|| url.startsWith("data:image/")
					|| element.hasAttr("cdn-exclude")) {
				continue;
			}

			String orgUrl = new String(url);

			// 以 / 开头的，需要添加 contextPath
			if (url.startsWith("/")) {
				if (contextPath.length() > 0 && url.startsWith(contextPath + "/") == false) {
					url = contextPath + url;
				}
			}

			// 以 ./ 开头的文件，需要添加模板路径
			else if (url.startsWith("./")) {
				url = contextPath + theme.getWebAbsolutePath() + url.substring(1);
			}

			// 直接是文件目录名开头
			else {
				url = contextPath + theme.getWebAbsolutePath() + "/" + url;
			}
			if (Options.getAsBool("cdn_enable")) {
				url = Options.get("cdn_domain") + url;
			}
			log.debug("处理过的URL：" + url);

			style = style.replace(orgUrl, url);

			log.debug("处理过的Style：" + style);

			element.attr("style", style);
		}
	}

	private void replace(Elements elements, String attrName) {
		Iterator<Element> iterator = elements.iterator();
		Theme theme = ThemeManager.me().getCurrentTheme();
		while (iterator.hasNext()) {

			Element element = iterator.next();
			String url = element.attr(attrName);

			// 处理src、href中的元素
			if (StrExtKit.isBlank(url) || url.startsWith("//")
					|| url.toLowerCase().startsWith("http")
					|| url.startsWith("data:image/")
					|| element.hasAttr("cdn-exclude")) {
				continue;
			}

			// 以 / 开头的，需要添加 contextPath
			if (url.startsWith("/")) {
				if (contextPath.length() > 0 && url.startsWith(contextPath + "/") == false) {
					url = contextPath + url;
				}
			}

			// 以 ./ 开头的文件，需要添加模板路径
			else if (url.startsWith("./")) {
				url = contextPath + theme.getWebAbsolutePath() + url.substring(1);
			}

			// 直接是文件目录名开头
			else {
				url = contextPath + theme.getWebAbsolutePath() + "/" + url;
			}
			if (Options.getAsBool("cdn_enable")) {
				url = Options.get("cdn_domain") + url;
			}

			element.attr(attrName, url);
		}
	}

	public static void main(String[] args) {
		String regex = "(?<=\\()(\\S+)(?=\\))";
		String content = "<div class=\"attention\">\r\n"
				+ "								<a class=\"attention-icon dib\" style=\"background-image: url('./images/xinlang1.png')\" target=\"_blank\" href=\"javascript:\" (asdf)></a>\r\n"
				+ "								<a class=\"attention-icon dib\" style=\"background-image: url('./images/xinlang2.png')\" target=\"_blank\" href=\"javascript:\"></a>\r\n"
				+ "								<a class=\"attention-icon dib\" style=\"background-image: url('./images/xinlang3.png')\" target=\"_blank\" href=\"javascript:\"></a>\r\n"
				+ "							</div>";
		Document doc = Jsoup.parse(content);
		Elements bgImgElements = doc.select("[style*=background-image]");
		Iterator<Element> iterator = bgImgElements.iterator();
		while (iterator.hasNext()) {
			Element element = iterator.next();
			String style = element.attr("style");

			System.out.println(style);
			style = getMatcher(regex, style);
			if ((style.startsWith("\'") && style.endsWith("\'")) || (style.startsWith("\"") && style.endsWith("\""))) {
				style = style.substring(1, style.length() - 1);
			}
			System.out.println(style);
		}
	}

	public static String getMatcher(String regex, String source) {
		String result = "";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(source);
		while (matcher.find()) {
			result = matcher.group(1);
		}
		return result;
	}
}
